package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 解析Mapper.xml文件
 * @author: xiangfeng
 * @date: 2021年09月28日
 */

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * <select id="selectOne" resultType="com.lagou.pojo.User" parameterType="com.lagou.pojo.User">
     *         select * from user where id=#{id} and username=#{username}
     * </select>
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectList = rootElement.selectNodes("//select");//获取所有的select标签
        List<Element> insertList = rootElement.selectNodes("//insert");
        List<Element> updateList = rootElement.selectNodes("//update");
        List<Element> deleteList = rootElement.selectNodes("//delete");


        for (Element element : selectList) {
            setParams(namespace, element,"SELECT");
        }
        for (Element element : insertList) {
            setParams(namespace, element,"INSERT");
        }
        for (Element element : updateList) {
            setParams(namespace, element,"UPDATE");
        }

        for (Element element : deleteList) {
            setParams(namespace, element,"DELETE");
        }
    }

    private void setParams(String namespace, Element element,String sqlType) {
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        String parameterType = element.attributeValue("parameterType");
        String sql = element.getTextTrim();//sql不是属性,是值
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setResultType(resultType);
        mappedStatement.setParameterType(parameterType);
        mappedStatement.setSql(sql);
        mappedStatement.setSqlType(sqlType);
        String key = namespace + "." + id;
        configuration.getMappedStatementMap().put(key, mappedStatement);
    }
}
